package com.huawei.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义没有权限访问处理器
 */
@Component
public class AppAccessDenyHandler implements AccessDeniedHandler {
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 处理访问被拒绝异常的方法
     *
     * @param request               HTTP请求对象
     * @param response              HTTP响应对象
     * @param accessDeniedException 访问被拒绝异常对象
     * @throws IOException      如果发生输入输出异常
     * @throws ServletException 如果发生Servlet异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=UTF-8");
        //构建需要返回的JSON数据
        BaseResult result = new BaseResult(-1, "您没有访问权限");
        //回写
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }

}
